package com.lexue.articlesync.controller;

import com.lexue.articlesync.entity.Article;
import com.lexue.articlesync.repository.ArticleRepository;
import com.lexue.articlesync.service.ContentSyncService;
import com.lexue.articlesync.service.FileUploadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 文章管理API控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/articles")
@RequiredArgsConstructor
public class ArticleController {
    
    private final ArticleRepository articleRepository;
    private final FileUploadService fileUploadService;
    private final ContentSyncService contentSyncService;
    
    /**
     * 获取文章列表
     */
    @GetMapping
    public ResponseEntity<Page<Article>> getArticles(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        
        Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Article> articles = articleRepository.findAll(pageable);
        
        return ResponseEntity.ok(articles);
    }
    
    /**
     * 根据ID获取文章
     */
    @GetMapping("/{id}")
    public ResponseEntity<Article> getArticle(@PathVariable Long id) {
        Optional<Article> article = articleRepository.findById(id);
        return article.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 搜索文章
     */
    @GetMapping("/search")
    public ResponseEntity<List<Article>> searchArticles(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String status) {
        
        List<Article> articles;
        
        if (title != null && !title.trim().isEmpty()) {
            articles = articleRepository.findByTitleContainingIgnoreCase(title);
        } else if (tag != null && !tag.trim().isEmpty()) {
            articles = articleRepository.findByTagsContaining(tag);
        } else if (status != null && !status.trim().isEmpty()) {
            try {
                Article.ArticleStatus articleStatus = Article.ArticleStatus.valueOf(status.toUpperCase());
                articles = articleRepository.findByStatus(articleStatus);
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().build();
            }
        } else {
            articles = articleRepository.findTop10ByOrderByCreatedAtDesc();
        }
        
        return ResponseEntity.ok(articles);
    }
    
    /**
     * 上传Markdown文件创建文章
     */
    @PostMapping("/upload")
    public ResponseEntity<Article> uploadMarkdown(
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String tags,
            @RequestParam(defaultValue = "true") Boolean isOriginal,
            @RequestParam(defaultValue = "false") Boolean joinActivity,
            @RequestParam(required = false) MultipartFile coverImage,
            @RequestParam(required = false) String description) {
        
        try {
            Article article = fileUploadService.uploadMarkdownFile(file, title, tags, isOriginal, joinActivity);
            
            // 处理封面图片
            if (coverImage != null && !coverImage.isEmpty()) {
                try {
                    String coverImagePath = fileUploadService.uploadCoverImage(coverImage);
                    article.setCoverImage(coverImagePath);
                    log.info("封面图片上传成功: {}", coverImagePath);
                } catch (Exception e) {
                    log.error("封面图片上传失败: {}", e.getMessage());
                    // 继续处理，但不设置封面图片
                }
            }
            
            // 设置描述信息
            if (description != null && !description.trim().isEmpty()) {
                article.setSummary(description);
            }
            
            Article savedArticle = articleRepository.save(article);
            
            log.info("文章上传成功: {}, 封面图片: {}", savedArticle.getId(), 
                    savedArticle.getCoverImage() != null ? "已设置" : "未设置");
            return ResponseEntity.ok(savedArticle);
            
        } catch (Exception e) {
            log.error("文章上传失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 创建或更新文章
     */
    @PostMapping
    public ResponseEntity<Article> createArticle(@RequestBody ArticleRequest request) {
        try {
            Article article = Article.builder()
                    .title(request.getTitle())
                    .content(request.getContent())
                    .htmlContent(request.getHtmlContent())
                    .summary(request.getSummary())
                    .coverImage(request.getCoverImage())
                    .tags(request.getTags())
                    .isOriginal(request.getIsOriginal() != null ? request.getIsOriginal() : true)
                    .joinActivity(request.getJoinActivity() != null ? request.getJoinActivity() : false)
                    .activityId(request.getActivityId())
                    .scheduledTime(request.getScheduledTime())
                    .status(Article.ArticleStatus.DRAFT)
                    .build();
            
            Article savedArticle = articleRepository.save(article);
            
            // 如果指定了平台，创建发布配置
            if (request.getPlatformIds() != null && !request.getPlatformIds().isEmpty()) {
                contentSyncService.createArticlePublishConfigs(savedArticle, request.getPlatformIds());
            }
            
            log.info("文章创建成功: {}", savedArticle.getId());
            return ResponseEntity.ok(savedArticle);
            
        } catch (Exception e) {
            log.error("文章创建失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新文章
     */
    @PutMapping("/{id}")
    public ResponseEntity<Article> updateArticle(@PathVariable Long id, @RequestBody ArticleRequest request) {
        Optional<Article> optionalArticle = articleRepository.findById(id);
        if (!optionalArticle.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Article article = optionalArticle.get();
            article.setTitle(request.getTitle());
            article.setContent(request.getContent());
            article.setHtmlContent(request.getHtmlContent());
            article.setSummary(request.getSummary());
            article.setCoverImage(request.getCoverImage());
            article.setTags(request.getTags());
            article.setIsOriginal(request.getIsOriginal() != null ? request.getIsOriginal() : article.getIsOriginal());
            article.setJoinActivity(request.getJoinActivity() != null ? request.getJoinActivity() : article.getJoinActivity());
            article.setActivityId(request.getActivityId());
            article.setScheduledTime(request.getScheduledTime());
            
            Article savedArticle = articleRepository.save(article);
            
            log.info("文章更新成功: {}", savedArticle.getId());
            return ResponseEntity.ok(savedArticle);
            
        } catch (Exception e) {
            log.error("文章更新失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除文章
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteArticle(@PathVariable Long id) {
        if (!articleRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            articleRepository.deleteById(id);
            log.info("文章删除成功: {}", id);
            return ResponseEntity.ok().build();
            
        } catch (Exception e) {
            log.error("文章删除失败: {}", id, e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 发布文章到指定平台
     */
    @PostMapping("/{id}/publish")
    public ResponseEntity<String> publishArticle(
            @PathVariable Long id,
            @RequestParam(required = false) List<Long> platformIds) {
        
        Optional<Article> optionalArticle = articleRepository.findById(id);
        if (!optionalArticle.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Article article = optionalArticle.get();
            
            // 如果指定了新的平台，创建发布配置
            if (platformIds != null && !platformIds.isEmpty()) {
                contentSyncService.createArticlePublishConfigs(article, platformIds);
            }
            
            // 异步发布
            contentSyncService.syncArticle(id);
            
            log.info("开始发布文章: {}", id);
            return ResponseEntity.ok("文章发布任务已启动");
            
        } catch (Exception e) {
            log.error("文章发布失败: {}", id, e);
            return ResponseEntity.badRequest().body("文章发布失败: " + e.getMessage());
        }
    }
    
    /**
     * 文章请求DTO
     */
    public static class ArticleRequest {
        private String title;
        private String content;
        private String htmlContent;
        private String summary;
        private String coverImage;
        private String tags;
        private Boolean isOriginal;
        private Boolean joinActivity;
        private String activityId;
        private LocalDateTime scheduledTime;
        private List<Long> platformIds;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getHtmlContent() { return htmlContent; }
        public void setHtmlContent(String htmlContent) { this.htmlContent = htmlContent; }
        
        public String getSummary() { return summary; }
        public void setSummary(String summary) { this.summary = summary; }
        
        public String getCoverImage() { return coverImage; }
        public void setCoverImage(String coverImage) { this.coverImage = coverImage; }
        
        public String getTags() { return tags; }
        public void setTags(String tags) { this.tags = tags; }
        
        public Boolean getIsOriginal() { return isOriginal; }
        public void setIsOriginal(Boolean isOriginal) { this.isOriginal = isOriginal; }
        
        public Boolean getJoinActivity() { return joinActivity; }
        public void setJoinActivity(Boolean joinActivity) { this.joinActivity = joinActivity; }
        
        public String getActivityId() { return activityId; }
        public void setActivityId(String activityId) { this.activityId = activityId; }
        
        public LocalDateTime getScheduledTime() { return scheduledTime; }
        public void setScheduledTime(LocalDateTime scheduledTime) { this.scheduledTime = scheduledTime; }
        
        public List<Long> getPlatformIds() { return platformIds; }
        public void setPlatformIds(List<Long> platformIds) { this.platformIds = platformIds; }
    }
}